<?php
/* 
 * Copyright (c) 2018-2021   All rights reserved.
 * 
 * 创建时间：2021-08-28 10:31
 *
 * 项目：rm  -  $  - PayController.php
 *
 * 作者：liwei 
 */

namespace modules\levpays\controllers;

use Lev;
use lev\base\Controllerv;
use lev\base\Requestv;
use lev\base\Viewv;
use lev\widgets\login\loginWidget;
use modules\levpays\BasePayIden;
use modules\levpays\sdk\wechatpay\h5\H5;
use modules\levpays\sdk\wechatpay\InstancePay;
use modules\levpays\sdk\wechatpay\jsapi\Jsapi;
use modules\levpays\sdk\wechatpay\native\Native;
use modules\levpays\table\tradesHelper;

!defined('INLEV') && exit('Access Denied LEV');


class PayController extends Controllerv
{
    public static function actionIndex() {

        $payIden  = Lev::stripTags(Lev::GPv('payIden')) ?: 'levpays';
        $goodsId  = Lev::stripTags(Lev::GPv('goodsId'));//可以多个商品，例如：1-2-3-4-10
        $paymoney = floatval(Lev::GPv('paymoney'));
        $tradeId  = floatval(Lev::GPv('tradeId'));

        static::payShow($payIden, $goodsId, $paymoney, $tradeId);
    }

    private static function payShow($payIden, $goodsId, $paymoney = 0, $tradeId = 0, $extParam = []) {
        Lev::$app['title'] = '支付金额';

        $paytypeid = Lev::checkAlipayUserAgent() ? 1 : (Lev::ckUserAgent('baiduboxapp/') ? 2 : 0);
        if ($tradeId) {
            $tradeInfo = tradesHelper::findOne(['id' => $tradeId]);
            if ($tradeInfo && !$tradeInfo['tradestatus']) {
                $payIden  = $tradeInfo['iden'];
                $uid      = $tradeInfo['uid'];
                $goodsId  = $tradeInfo['goodsid'];
                $paymoney = $tradeInfo['paymoney'];
                //$paytypeid= $tradeInfo['paytypeid'];
            }else {
                $tradeId = 0;
            }
        }

        isset($uid) || $uid = Lev::$app['uid'];

        $goodsInfo = BasePayIden::getPayGoodsInfoByIden($payIden, $uid, $goodsId, $paymoney, $tradeId, $extParam);
        if (empty($goodsInfo)) {
            Lev::showMessages('抱歉，没有找到商品信息，支付失败');
        }elseif (Lev::arrv('status', $goodsInfo, 0) <0) {
            Lev::showMessages($goodsInfo);
        }

        $currencys = tradesHelper::currency();
        $ency = isset($currencys[$goodsInfo['ency']]) ? $goodsInfo['ency'] : 'CNY';

        Viewv::render(dirname(__DIR__) . '/template/renders/pay/index.php', [
            'paymoney'   => Lev::formatMoney($goodsInfo['paymoney']),
            'unit'       => $currencys[$ency]['unit'],
            'goods'      => $goodsInfo, //$goodsInfo['lists'] = 存入多个商品
            'paytypeid'  => $paytypeid,
            'paytypeids' => tradesHelper::paytypeid(),
            'paytypeidIcons' => tradesHelper::paytypeidIcon(),
        ]);
    }

    public static function actionPaySign() {
        $tradeId   = floatval(Lev::GPv('tradeId'));
        $appid     = Lev::stripTags(Lev::GPv('appid'));
        $method    = Lev::stripTags(Lev::GPv('method')) ?: 'JSAPI';
        $tradeInfo = tradesHelper::findOne(['id'=>$tradeId]);
        $prepay_id = Jsapi::PlaceOrder(tradesHelper::getTradeno($tradeInfo['id']), $tradeInfo['name'], $tradeInfo['paymoney'], $method, $appid);
        $paySign = InstancePay::paySign($prepay_id, $appid);
        echo json_encode(Lev::responseMsg(1, '', ['paySign'=>$paySign]));
    }

    /**
     * 查询支付订单
     */
    public static function actionCheckTradeNo() {
        $paytypeid = intval(Lev::GPv('paytypeid'));
        if ($paytypeid == 1) {
            Lev::actionControllerAction('pay', 'CheckTradeNo', 'alipay');
            return;
        }elseif ($paytypeid == 2) {
            Lev::actionControllerAction('pay', 'CheckTradeNo', 'baidupay');
            return;
        }
        $tradeNo = Lev::stripTags(Lev::GPv('tradeNo'));
        $pre = Lev::stripTags(Lev::GPv('pre'));
        $res = InstancePay::checkTradeNo(InstancePay::getOutTradeNo($tradeNo, $pre));
        if ($res['_paySuccess']) {
            InstancePay::paySuccess(['message'=>'已支付'], $tradeNo, $pre, $res);
            $location = loginWidget::getLoginReferer() ?: 1;
            echo json_encode(Lev::responseMsg(1, '支付成功', ['location'=>$location]));
        }elseif ($res['trade_state'] == 'NOTPAY' || $res['code'] == 'ORDER_NOT_EXIST') {//未支付
            echo json_encode(Lev::responseMsg(2, '',[Lev::$app['isAdmin']? $res :'']));
        }else {
            echo json_encode(Lev::responseMsg(-2, $res['message'].'-'.$res['trade_state_desc'], [Lev::$app['isAdmin']? $res :'']));
        }
    }

    /**
     * 支付结果异步通知
     */
    public static function actionNotify() {
        ob_end_clean();
        echo InstancePay::notify();
    }

    /**
     * 微信小程序调起支付
     */
    public static function actionWxmini() {
        $appid = Lev::stripTags(Lev::GPv('appid'));
        $tradeno = Lev::stripTags(Lev::GPv('tradeNo'));
    }

}